// src/pages/PatientData/DiseaseBigData.jsx
// 疾病大数据页面
import React, { useEffect, useRef, useState, useCallback } from 'react';
import '../../../styles/DiseaseBigData.css';
import * as echarts from 'echarts';
import {
  getDiseaseData, // 获取疾病大数据的接口
} from '../../../request/wgqApi';

function DiseaseBigData() {
    // 获取 Dom 节点的引用
    const chartTopItemOne = useRef(null);
    const chartTopItemTwo = useRef(null);
    const chartTopItemThree = useRef(null);
    const chartTopItemFour = useRef(null);
    const chartMiddleLeftItemOne = useRef(null);
    const chartMiddleLeftItemTwo = useRef(null);
    const chartBottom = useRef(null);

    // 状态管理
    const [doctorData, setDoctorData] = useState([]);
    const [registerCharts, setRegisterCharts] = useState({});
    const [equipCharts, setEquipCharts] = useState({});
    const [isLoading, setIsLoading] = useState(true);
    const [drugsCharts, setDrugsCharts] = useState({});
    const [vaccinesCharts, setVaccinesCharts] = useState({});
    const [curTopThree, setCurTopThree] = useState([]);
    const [weekTopThree, setWeekTopThree] = useState([]);
    const [typeCharts, setTypeCharts] = useState([]);

    // 获取疾病大数据的方法
    const fetchDiseaseData = useCallback(async () => {
        try {
            const res = await getDiseaseData();
            if (res.code === 1) {
                const data = res.data;
                setDoctorData(data.doctorList);
                setRegisterCharts(data.registerCharts);
                setEquipCharts(data.equipCharts);
                setDrugsCharts(data.drugsCharts);
                setVaccinesCharts(data.vaccinesCharts);
                setCurTopThree(data.curTop3);
                setWeekTopThree(data.weekTop3);
                setTypeCharts(data.typeCharts);
                setIsLoading(false);
            } else {
                console.error('API返回错误信息:', res.msg);
            }
        } catch (error) {
            console.error('获取疾病大数据失败:', error);
            setIsLoading(false);
        }
    }, []);

    useEffect(() => {
        // 初次加载数据
        fetchDiseaseData();

        // 实现轮询，每5秒刷新一次数据
        const interval = setInterval(() => {
            fetchDiseaseData();
        }, 5000);

        // 组件卸载时清除定时器
        return () => clearInterval(interval);
    }, [fetchDiseaseData]);

    useEffect(() => {
        // 初始化图表实例
        let myChartOne, myChartTwo, myChartThree, myChartFour, myChartMiddleLeftItemOne, myChartMiddleLeftItemTwo, myChartBottom;

        if (chartTopItemOne.current) {
            myChartOne = echarts.init(chartTopItemOne.current);
            const optionOne = {
                polar: {
                    radius: [10, '80%'],
                },
                angleAxis: {
                    max: 550,
                    startAngle: 75,
                },
                radiusAxis: {
                    type: 'category',
                    data: registerCharts.type || [],
                },
                tooltip: {},
                series: {
                    type: 'bar',
                    data: registerCharts.data || [],
                    coordinateSystem: 'polar',
                    label: {
                        show: true,
                        position: 'middle',
                        formatter: '{b}: {c}',
                    },
                },
            };
            myChartOne.setOption(optionOne);
        }

        if (chartTopItemTwo.current) {
            myChartTwo = echarts.init(chartTopItemTwo.current);
            const optionTwo = {
                title: {
                    text: equipCharts.total || '0',
                    subtext: '医疗器材消耗',
                    left: 'center',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: equipCharts.type || [],
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        data: equipCharts.data || [],
                        type: 'line',
                        areaStyle: {},
                    },
                ],
            };
            myChartTwo.setOption(optionTwo);
        }

        if (chartTopItemThree.current) {
            myChartThree = echarts.init(chartTopItemThree.current);
            const optionThree = {
                title: {
                    text: drugsCharts.total || '0',
                    subtext: '药品消耗',
                    left: 'center',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: drugsCharts.type || [],
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        data: drugsCharts.data || [],
                        type: 'line',
                        areaStyle: {},
                    },
                ],
            };
            myChartThree.setOption(optionThree);
        }

        if (chartTopItemFour.current) {
            myChartFour = echarts.init(chartTopItemFour.current);
            const optionFour = {
                title: {
                    text: vaccinesCharts.total || '0',
                    subtext: '疫苗综合消耗',
                    left: 'center',
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    data: vaccinesCharts.type || [],
                },
                yAxis: {
                    type: 'value',
                },
                series: [
                    {
                        data: vaccinesCharts.data || [],
                        type: 'line',
                        areaStyle: {},
                        label: {
                            show: true,
                            position: 'top',
                            formatter: function (params) {
                                const xAxisData = vaccinesCharts.type || [];
                                const index = xAxisData.indexOf(params.name);
                                return xAxisData[index] + ': ' + params.value;
                            },
                        },
                    },
                ],
            };
            myChartFour.setOption(optionFour);
        }

        if (chartMiddleLeftItemOne.current) {
            myChartMiddleLeftItemOne = echarts.init(chartMiddleLeftItemOne.current);
            const optionMiddleLeftItemOne = {
                title: {
                    text: '当前科室 TOP3',
                    left: 'center',
                },
                polar: {
                    radius: [10, '75%'],
                },
                radiusAxis: {
                    max: 600,
                },
                angleAxis: {
                    type: 'category',
                    data: curTopThree.map(item => item.name) || [],
                    startAngle: 75,
                },
                tooltip: {},
                series: {
                    type: 'bar',
                    data: curTopThree.map(item => item.value) || [],
                    coordinateSystem: 'polar',
                    label: {
                        show: true,
                        position: 'middle',
                        formatter: '{b}: {c}',
                    },
                },
                animation: false,
            };
            myChartMiddleLeftItemOne.setOption(optionMiddleLeftItemOne);
        }

        if (chartMiddleLeftItemTwo.current) {
            myChartMiddleLeftItemTwo = echarts.init(chartMiddleLeftItemTwo.current);
            const optionMiddleLeftItemTwo = {
                title: {
                    text: '本周科室 TOP3',
                    left: 'center',
                },
                polar: {
                    radius: [10, '75%'],
                },
                radiusAxis: {
                    max: 6000,
                },
                angleAxis: {
                    type: 'category',
                    data: weekTopThree.map(item => item.name) || [],
                    startAngle: 75,
                },
                tooltip: {},
                series: {
                    type: 'bar',
                    data: weekTopThree.map(item => item.value) || [],
                    coordinateSystem: 'polar',
                    label: {
                        show: true,
                        position: 'middle',
                        formatter: '{b}: {c}',
                    },
                },
                animation: false,
            };
            myChartMiddleLeftItemTwo.setOption(optionMiddleLeftItemTwo);
        }

        if (chartBottom.current) {
            myChartBottom = echarts.init(chartBottom.current);
            const optionBottom = {
                legend: {},
                tooltip: {},
                dataset: {
                    source: [
                        ['科室', '等待人次', '待缴费', '复诊'],
                        ...convertTypeChartsData(typeCharts),
                    ],
                },
                xAxis: { type: 'category' },
                yAxis: {},
                series: [
                    { type: 'bar' },
                    { type: 'bar' },
                    { type: 'bar' }
                ],
            };
            myChartBottom.setOption(optionBottom);
        }

        // 清理函数，销毁图表实例
        return () => {
            if (myChartOne) myChartOne.dispose();
            if (myChartTwo) myChartTwo.dispose();
            if (myChartThree) myChartThree.dispose();
            if (myChartFour) myChartFour.dispose();
            if (myChartMiddleLeftItemOne) myChartMiddleLeftItemOne.dispose();
            if (myChartMiddleLeftItemTwo) myChartMiddleLeftItemTwo.dispose();
            if (myChartBottom) myChartBottom.dispose();
        };
    }, [registerCharts, typeCharts, equipCharts, drugsCharts, vaccinesCharts, curTopThree, weekTopThree]);

    /**
     * 转换typeCharts数据格式以适应ECharts
     * @param {object} typeCharts
     * @returns {Array} 转换后的数据数组
     */
    function convertTypeChartsData(typeCharts) {
        const result = [];
        if (
            typeCharts &&
            typeCharts.type &&
            typeCharts.repeatdata &&
            typeCharts.waitdata &&
            typeCharts.waitpaydata
        ) {
            for (let i = 0; i < typeCharts.type.length; i++) {
                result.push([
                    typeCharts.type[i],
                    typeCharts.waitdata[i],
                    typeCharts.waitpaydata[i],
                    typeCharts.repeatdata[i]
                ]);
            }
        }
        return result;
    }

    return (
        <div className="DiseaseBigDataBox">
            <div className="DiseaseBigDataTop">
                <div className="DiseaseBigDataTopItem">
                    <div ref={chartTopItemOne} className="DiseaseBigDataTopItemChart"></div>
                </div>
                <div className="DiseaseBigDataTopItem">
                    <div ref={chartTopItemTwo} className="DiseaseBigDataTopItemChart"></div>
                </div>
                <div className="DiseaseBigDataTopItem">
                    <div ref={chartTopItemThree} className="DiseaseBigDataTopItemChart"></div>
                </div>
                <div className="DiseaseBigDataTopItem">
                    <div ref={chartTopItemFour} className="DiseaseBigDataTopItemChart"></div>
                </div>
            </div>
            <div className="DiseaseBigDataMiddle">
                <div className="DiseaseBigDataMiddleLeft">
                    <div className="DiseaseBigDataMiddleLeftItem">
                        <div ref={chartMiddleLeftItemOne} className="DiseaseBigDataMiddleLeftItemChart"></div>
                    </div>
                    <div className="DiseaseBigDataMiddleLeftItem">
                        <div ref={chartMiddleLeftItemTwo} className="DiseaseBigDataMiddleLeftItemChart"></div>
                    </div>
                </div>
                <div className="DiseaseBigDataMiddleRight">
                    <div className='DiseaseBigDataMiddleRightTitle'>今日医生</div>
                    <div className='DiseaseBigDataMiddleRightItem'>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>医生</div>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>科室</div>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>看诊人次</div>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>本周处方</div>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>患者满意度</div>
                        <div className='DiseaseBigDataMiddleRightItemTitle'>医院评级</div>
                    </div>
                    {
                        isLoading ? (
                            <div>加载中...</div>
                        ) : (
                            doctorData.map(item => (
                                <div className='DiseaseBigDataMiddleRightItem' key={item.name}>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.name}</div>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.department}</div>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.count}</div>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.file}</div>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.rating}</div>
                                    <div className="DiseaseBigDataMiddleRightItemList">{item.type}</div>
                                </div>
                            ))
                        )
                    }
                </div>
            </div>
            <div className="DiseaseBigDataBottom">
                <div ref={chartBottom} className="DiseaseBigDataBottomChart"></div>
            </div>
        </div>
    );
}

export default DiseaseBigData;